/*
 * Graph - Graphs are 2d arrays, but wrapped with abstract functions
 *
 * Copyright 2007 James W. Hofmann
 *
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

import lib3f.IntPoint;

typedef Graph2D = Array<Array<GameTile>>;

class Graph
{

	public static function init(xsize : Int, ysize : Int) : Graph2D
	{
		var ag : Graph2D = new Array();
		
		for (x in 0...xsize)
		{
			var strip : Array<GameTile> = new Array();
			for (y in 0...ysize)
			{
				var nt = new GameTile(x,y);
				strip.push(nt);
			}
			ag.push(strip);
		}
				
		for (x in 0...ag.length)
		{
			for (y in 0...ag[0].length)
			{
				var ts = ag[x][y];
				var xl : GameTile;
				var xr : GameTile;
				var yl : GameTile;
				var yr : GameTile;
				xl = null;
				xr = null;
				yl = null;
				yr = null;
				if (x>0)
					xl = ag[x-1][y];
				if (y>0)
					yl = ag[x][y-1];
				if (x<ag.length-1)
					xr = ag[x+1][y];
				if (y<ag[0].length-1)
					yr = ag[x][y+1];
				ts.link(xl,xr,yl,yr);
			}		
		}		

		return ag;
		
	}

	public static function iter(graph : Graph2D) : IterGraph
	{
		return new IterGraph(0,0,graph.length,graph[0].length,graph);
	}
	
	public static function getsize(graph : Graph2D) : IntPoint
	{
		return new IntPoint(graph.length, graph[0].length);
	}
	
	public static function inbounds(x : Int, y : Int, graph : Graph2D) : Bool
	{
		var size : IntPoint = getsize(graph);
		return (x>=0 && y>=0 && x<size.x && y<size.y);
	}
	
}

class IterGraph {

	var minx: Int;
	var curx: Int;
	var miny: Int;
	var maxx: Int;
	var maxy: Int;
	var element: Graph2D;
	
	public function new(minx : Int, miny : Int, maxx : Int, maxy : Int, element : Graph2D)
	{
		this.minx = minx;
		this.curx = minx;
		this.miny = miny;
		this.maxx = maxx;
		this.maxy = maxy;
		this.element = element;
	}

	public function hasNext()
	{
		return (miny!=maxy-1 || (curx!=maxx));
	}
	
	public function next() : GameTile
	{
		if (curx==maxx)
		{
			curx=minx;
			miny++;
		}
		return element[curx++][miny];
	}
	
}
